package com.sz.sboot.config;

import com.sz.sboot.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component    //配置拦截器；
public class JwtInterceptor  implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String header = request.getHeader("Auth");
        if (header != null && header.startsWith("zhiling")){
            String token  = header.substring(7);
            Claims claims = jwtUtils.parseToken(token);
            System.out.println(token);
            if (claims!=null){
                System.out.println(claims.getId());
                System.out.println(claims.getIssuedAt());
                System.out.println(claims.getExpiration());//与当前的系统时间进行比对； 如果大于系统时间说明已经过期！！！
                System.out.println(claims.getSubject());

                String roles = claims.get("roles").toString();
                if (roles!=null && roles.equals("deleteRoles")){
                    request.setAttribute("roles",roles);
                }
            }else {
                return false; //就此终止，无法继续访问！！！
            }
        }
        return true;
    }
}
